<template>
  <div class="bigBox">
    <div style="width: 60%;height: 100%; margin: 0 auto;overflow-y: auto; padding-bottom: 20px;box-sizing: border-box;">
      <span class="titleSpan">
        <p>任务名称: </p>
        <input v-model="jsonData.inputTitle" placeholder="任务名称" />
      </span>
      <seleModelStyles @openLoginFun="openLoginFun" @changeStyle="changeStyle" @changeSize="changeSize"
        @changeNum="changeNum" :jsonData="jsonData" />
      <div class="leftItem">
        <p>关键词输入：</p>
        <el-input v-model="jsonData.prompt" :rows="8" type="textarea" resize='none' placeholder="请输入您的提示词，支持中英文" />
      </div>
      <div class="leftItem">
        <p>反向提示词：</p>
        <el-input v-model="jsonData.negative_prompt" :rows="6" type="textarea" resize='none'
          placeholder="请输入您的反向提示词，支持中英文" />
      </div>
      <el-button class="paintBtn" @click="addTask" :loading="loadFlag">{{ '立即生成（-' + pegg * jsonData.imgNum
        + '皮蛋）' }}</el-button>

    </div>
    <!-- 留在当前页的对话框 -->
    <el-dialog v-model="waitFlag" align-center title="任务已提交" width="30%">
      <span>您的任务已提交，您可以返回上一页，或者继续提交任务</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="waitFlag = false">继续提交</el-button>
          <el-button type="primary" @click="backTask()"> 返回 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, reactive, onUnmounted } from "vue";
import $apiFun from "/src/request/api";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import seleModelStyles from "../../components/seleModelStyles.vue";
import { getUid, upUserInfoData } from "../../../hooks/auth";
//定义要发送的emit事件
const emit = defineEmits(['openLogin'])

// const { uid, auth_token } = auth_store.auth;
const router = useRouter();

const btnBox = ref(null); //顶部按钮组元素盒
const loadFlag = ref(false); //按钮加载状态
const pegg = ref(2); //扣除皮蛋数

const query = router.currentRoute.value.query;
const waitFlag = ref(false); // 后台挂载对话框
const jsonData = reactive({
  modelSele: "", //选择的模型
  size: Number(query.size) || 2, //选择的尺寸
  taskId: query.task_id,
  inputTitle: query.title, // 标题
  negative_prompt: query.negative_prompt,//反向提示词
  prompt: query.prompt, //输入正文
  style_id: query.style_id,
  imgNum: Number(query.num) || 10, //分镜数量
  createtime: "", //创建时间
  width: 512,
  height: 512
});
//未登录，打开登录页
const openLoginFun = () => {
  emit('openLogin', true)
}

//获取任务详情,获取上一次的输入内容
const getTaskInfo = () => {
  $apiFun.ScriptTaskInfo({ uid: getUid(), spec: query }).then((res) => {
    console.log("获取任务详情", res);
    if (res.code == 200) {
      let data = res.data
      try {
        data = JSON.parse(res.data)
      } catch (error) {

      }
      data.scenes.forEach(val1 => {
        val1.imgs.forEach(val2 => {
          jsonData.prompt = val2.prompt
        })
      })
      jsonData.negative_prompt = query.negative_prompt
    }
  });
}
//切换选中模型
const changeStyle = (modelItem) => {
  jsonData.modelSele = modelItem
  if (typeof modelItem.preset_info == 'string') {
    modelItem.preset_info = JSON.parse(modelItem.preset_info)
  }
  jsonData.prompt = modelItem.preset_info.prompt
  jsonData.negative_prompt = modelItem.preset_info.negative_prompt
}
// //切换生成数量
const changeNum = (data) => {
  jsonData.imgNum = data
  console.log(data)
}
//更改尺寸
const changeSize = (data) => {
  jsonData.width = data[0]
  jsonData.height = data[1]
  jsonData.size = data[2]
  console.log(data)
}
onMounted(() => {
  if (query.task_id) {
    getTaskInfo()
  }
});

// 添加任务
const addTask = async (hd) => {
  if (!jsonData.inputTitle) {
    ElMessage.error("请输入任务名称");
    return false;
  }
  if (!jsonData.prompt) {
    ElMessage.error("请输入描述词");
    return false;
  }
  // 按钮加载效果
  loadFlag.value = true;
  //预置参数
  const preSet = jsonData.modelSele.preset_info
  //组装请求数据
  let req = {
    uid: getUid(),
    pegg: pegg.value * 20 * jsonData.imgNum,
    type: 2,
    style_id: jsonData.modelSele.id,
    //存储信息，复制时需要使用
    req_json: {
      num: jsonData.imgNum,
      // negative_prompt: jsonData.negative_prompt,
      img_size: jsonData.size
    },
    spec: {
      scenes: await matePrompt(jsonData.prompt),
      title: jsonData.inputTitle,
      icon: jsonData.modelSele.icon,
      detection: true, //是否鉴黄
      model: 1.4,
      ai_paint: {
        model: jsonData.modelSele.model_class,
        width: jsonData.width,
        height: jsonData.height,
        steps: preSet.steps || 28,
        cfg_scale: preSet.cfg_scale || 10,
        style_name: preSet.style_name,
        lora: preSet.lora,
        sampling: preSet.sampling,
        negative_prompt: jsonData.negative_prompt,
        batch_size: 1,
        seed: -1,
      },
    },
  };
  req.spec.hd = {
    scale: 2,
    strength: 0.6,
  };
  $apiFun.addScriptTask(req).then((res) => {
    console.log("addScriptTask", res);
    if (res.code == 200) {
      jsonData.taskId = res.data.task_id;
      if (res.code == 200 && !!res.data.task_id) {
        waitFlag.value = true; //后台挂载弹窗
      }
    } else {
      ElMessage.warning(res.msg)
      loadFlag.value = false;
    }
  });
};

//组装提示词
const matePrompt = async (text) => {
  let scenes = [[]];
  const pattern = /[\u4e00-\u9fa5]/; // 使用Unicode范围匹配中文字符
  if (pattern.test(text)) {
    await $apiFun.Fanyi({ q: text, to: "en" }).then((res) => {
      try {
        text = res.trans_result[0].dst
      } catch (error) {
      }
    })
  }
  console.log(text)
  for (let i = 0; i < jsonData.imgNum; i++) {
    scenes[0].push({ sentence: text, desc: text, roles: [] });
  }
  return scenes;
};

//返回批量生图主页面
const backTask = () => {
  waitFlag.value = false;
  loadFlag.value = false;
  router.push({
    name: "batchCreate",
  });
};


</script>
<style scoped>
.paintBtn {
  width: 100%;
  height: 40px;
  opacity: 1;
  border-radius: 20px;
  margin-top: 20px;
  background: rgba(56, 56, 56, 1);
  border: 0px;
  /** 文本1 */
  font-size: 12px;
  color: rgba(255, 255, 255, 1);
}

.leftItem p {
  font-size: 16px;
  font-weight: 500;
  line-height: 23.17px;
  color: rgba(0, 0, 0, 1);
  margin: 10px 0;
}

.leftItem {
  position: relative;
  padding: 10px 0;
}

.titleSpan p {
  display: inline-block;
  margin-right: 8px;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 1);
  vertical-align: middle;
}

input:focus {
  outline: none;
}

.titleSpan input {
  width: 168px;
  height: 30px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(229, 229, 229, 1);
  font-size: 12px;
  font-weight: 400;
  color: rgba(166, 166, 166, 1);
  padding-left: 8px;
  box-sizing: border-box;
}

.titleSpan {
  display: block;
  height: 30px;
}
</style>
<!-- 全局和头部 -->
<style scoped>
.bigBox {
  position: relative;
  width: 100%;
  height: 100%;
  /* background-color: red; */
  box-sizing: border-box;
  padding: 40px 100px 0px 68px;
}
</style>
